package cn.cmkj.auction.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jude.rollviewpager.RollPagerView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.util.LogUtil;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.MainRecommendAdapter;
import cn.cmkj.auction.adapter.MainRollPagerAdapter;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.http.MainAdvertise;
import cn.cmkj.auction.data.http.MainNotice;
import cn.cmkj.auction.data.http.MainRecommend;
import cn.cmkj.auction.ui.GoodsListByTagActivity;
import cn.cmkj.auction.ui.GoodsSearchActivity;
import cn.cmkj.auction.ui.ShuhuaListActivity;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.widget.MyScrollView;
import cn.cmkj.auction.widget.TextScrollBanner;

/**
 * Created by cunguoyao on 2017/8/13.
 */
@ContentView(R.layout.fragment_main_home)
public class MainHomeFragment extends BaseFragment implements /*MyScrollView.ScrollViewListener,*/SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    @ViewInject(R.id.swipeRefreshLayout)
    private SwipeRefreshLayout swipeRefreshLayout;
    @ViewInject(R.id.scrollView)
    private MyScrollView scrollView;
    @ViewInject(R.id.roll_view_pager)
    private RollPagerView rollPagerView;
    @ViewInject(R.id.ll_search)
    private LinearLayout searchLayout;
    @ViewInject(R.id.text_scroll)
    private TextScrollBanner textScrollBanner;
    @ViewInject(R.id.l_main_home_guohua)
    private RelativeLayout guohuaLayout;
    @ViewInject(R.id.l_main_home_youhua)
    private RelativeLayout youhuaLayout;
    @ViewInject(R.id.l_main_home_shufa)
    private RelativeLayout shufaLayout;
    @ViewInject(R.id.l_main_home_yansp)
    private RelativeLayout yanspLayout;

    @ViewInject(R.id.main_content_layout)
    private LinearLayout contentLayout;

    private int height;
    private boolean requesting = false;
    private MainRollPagerAdapter mainRollPagerAdapter;
    private List<MainAdvertise> rollAds;
    private List<MainNotice> scrollTextData;
    private List<MainRecommend> mData;

    public static MainHomeFragment create() {
        MainHomeFragment f = new MainHomeFragment();
        Bundle args = new Bundle();
        //args.putInt("type", type);
        f.setArguments(args);
        return f;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rollAds = new ArrayList<>();
        scrollTextData = new ArrayList<>();
        mData = new ArrayList<>();
        mainRollPagerAdapter = new MainRollPagerAdapter(getActivity(), rollAds);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = x.view().inject(this, inflater, container);
        //获取顶部图片高度后，设置滚动监听
        ViewTreeObserver vto = rollPagerView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rollPagerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = rollPagerView.getHeight();
                rollPagerView.getWidth();
                //scrollView.setScrollViewListener(MainHomeFragment.this);
            }
        });
        rollPagerView.setAdapter(mainRollPagerAdapter);
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                fetchMainData();
            }
        });
        searchLayout.setOnClickListener(this);
        guohuaLayout.setOnClickListener(this);
        youhuaLayout.setOnClickListener(this);
        shufaLayout.setOnClickListener(this);
        yanspLayout.setOnClickListener(this);
        return view;
    }

    @Override
    public void onRefresh() {
        if(!requesting) {
            fetchMainData();
        }
    }

    private void fetchMainData() {
        requesting = true;
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.homeIndex);
        x.http().request(HttpMethod.POST, params, new HttpCallback(getActivity()) {
            @Override
            public void success(String s) {
                requesting = false;
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
                //结束后停止刷新
                LogUtil.e("----s---" + s);
                JSONObject jsonStr = null;
                try {
                    jsonStr = new JSONObject(s);
                    JSONObject jsonObject = jsonStr.optJSONObject("data");
                    JSONArray advListArray = jsonObject.optJSONObject("advment").optJSONArray("advlist");
                    JSONArray notice = jsonObject.optJSONArray("notice");
                    JSONArray recommend = jsonObject.optJSONArray("recommend");
                    rollAds.clear();
                    rollAds.addAll(MainAdvertise.parseJsonArray(advListArray));
                    scrollTextData.clear();
                    scrollTextData.addAll(MainNotice.parseJsonArray(notice));
                    mData.clear();
                    mData.addAll(MainRecommend.parseJsonArray(recommend));

                    mainRollPagerAdapter.notifyDataSetChanged();
                    textScrollBanner.setList(scrollTextData);
                    textScrollBanner.startScroll();
                    resolveRecommendData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                //结束后停止刷新
                requesting = false;
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }

            @Override
            public void cancel(CancelledException e) {
                //结束后停止刷新
                requesting = false;
                swipeRefreshLayout.post(new Runnable() {
                    @Override
                    public void run() {
                        swipeRefreshLayout.setRefreshing(false);
                    }
                });
            }
        });
    }

    private void resolveRecommendData() {
        if(mData != null && mData.size() > 0) {
            for(final MainRecommend mainRecommend : mData) {
                LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
                linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                View recommendView = LayoutInflater.from(getActivity()).inflate(R.layout.view_main_item, null);
                TextView titleText = (TextView)recommendView.findViewById(R.id.main_item_text_center);
                RecyclerView recommendRecycleView = (RecyclerView)recommendView.findViewById(R.id.recyclerView);
                ImageView left = (ImageView)recommendView.findViewById(R.id.iv_left);
                ImageView right = (ImageView)recommendView.findViewById(R.id.iv_right);
                recommendRecycleView.setLayoutManager(linearLayoutManager);
                recommendRecycleView.addOnScrollListener(new IOnScrollChangeListener(linearLayoutManager, left, right));
                titleText.setText(mainRecommend.getTitle());
                List<MainRecommend.MainRecommendGoods> goodsList = mainRecommend.getGoods();
                MainRecommendAdapter adapter = new MainRecommendAdapter(getActivity(), goodsList);
                recommendRecycleView.setAdapter(adapter);
                RelativeLayout layoutGetMore = (RelativeLayout) recommendView.findViewById(R.id.layout_get_more);
                layoutGetMore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(getActivity(), GoodsListByTagActivity.class);
                        intent.putExtra("tag", mainRecommend.getType());
                        intent.putExtra("tag_name", mainRecommend.getTitle());
                        startActivity(intent);
                    }
                });
                contentLayout.addView(recommendView);
            }
        }
    }

    private class IOnScrollChangeListener extends RecyclerView.OnScrollListener {

        private ImageView left;
        private ImageView right;
        private LinearLayoutManager mLayoutManager;
        private boolean loading = true;
        int pastVisiblesItems, visibleItemCount, totalItemCount;

        public IOnScrollChangeListener(LinearLayoutManager layoutManager, ImageView left, ImageView right) {
            this.left = left;
            this.right = right;
            this.mLayoutManager = layoutManager;
        }

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
            if (loading) {
                if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                    // 判断点
                    Log.v("...", "Last Item Wow !");
                    right.setVisibility(View.GONE);
                    left.setVisibility(View.VISIBLE);
                }
                if(pastVisiblesItems == 0) {
                    right.setVisibility(View.VISIBLE);
                    left.setVisibility(View.GONE);
                }
            }
        }
    }

    /*@Override
    public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
        if(y<=height && y>=0){
            float scale =(float) y /height;
            float alpha =  (255 * scale);
            searchLayout.setBackgroundColor(Color.argb((int) alpha, 0xff, 0xff, 0xff));
        }
        else if(y > height){
            searchLayout.getBackground().setAlpha(255);
        }
    }*/

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_search:
                Intent intent = new Intent(getActivity(), GoodsSearchActivity.class);
                startActivity(intent);
                break;
            case R.id.l_main_home_guohua:
                Intent intent1 = new Intent(getActivity(), ShuhuaListActivity.class);
                intent1.putExtra("chooseCate", 24);
                intent1.putExtra("chooseCateName", "国画");
                startActivity(intent1);
                break;
            case R.id.l_main_home_youhua:
                Intent intent2 = new Intent(getActivity(), ShuhuaListActivity.class);
                intent2.putExtra("chooseCate", 25);
                intent2.putExtra("chooseCateName", "油画");
                startActivity(intent2);
                break;
            case R.id.l_main_home_shufa:
                Intent intent3 = new Intent(getActivity(), ShuhuaListActivity.class);
                intent3.putExtra("chooseCate", 27);
                intent3.putExtra("chooseCateName", "书法");
                startActivity(intent3);
                break;
            case R.id.l_main_home_yansp:
                Intent intent4 = new Intent(getActivity(), ShuhuaListActivity.class);
                intent4.putExtra("chooseCate", 28);
                intent4.putExtra("chooseCateName", "衍生品");
                startActivity(intent4);
                break;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
